<?php
namespace app\applet\controller;

use app\applet\model\HouseKeeper;
use app\manage\model\ApartmentSettings;
use app\manage\model\ContracTmanagement;
use app\manage\model\ElectricityBill;
use app\manage\model\EstateBill;
use app\manage\model\GasBill;
use app\manage\model\NetBill;
use app\manage\model\TenantManagement;
use app\manage\model\WaterBill;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;
use WeixinPay\WeixinPay;

class WxPay extends Controller {
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
    }

    /**
     * 小程序支付后的回调
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function notify()
    {
        $xml = file_get_contents('php://input'); //接受通知参数；
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result)
        {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $trade_type   = $result['trade_type'];  //判断是否是jsapi支付
            $real_money = $result['total_fee'] / 100;
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')
            {
                // 如何找到对应的账单？？？
                $model['e'] = new ElectricityBill();
                $model['w'] = new WaterBill();
                $model['g'] = new GasBill();
                $model['n'] = new NetBill();
                $model['s'] = new EstateBill();
                foreach ($model as $m) {
                    if ($detail = $m->index_out_trade_no($out_trade_no)) {
                        $a = new ApartmentSettings();
                        foreach ($detail as $value) {
                            $setting = $a->index2($value['admin_id']);
                            $status = date('d') <= ($setting['settlement_time'] + $setting['date_time']) ? '2' : '3';
                            $data = [
                                'cost_method' => '4',
                                'status' => $status,
                                'time' => time()
                            ];
                            $m->m_update($value['id'], $data);
                        }
                    } else {
                        continue;
                    }
                }
                echo 'SUCCESS';
            } else {
                echo 'FAIL';
            }
        }
    }

    /**
     * 小程序支付
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pay() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['bill_id', 'require', '订单id不能为空'],
            ['type', 'require', '缴费类型不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $bill_id = $input['bill_id'];
        $type = $input['type'];
        $this->is_prohibit($id);
        $model = new HouseKeeper();
        $detail = $model->detail($id);

        $openid = $detail['open_id'];
        $out_trade_no = getMicrosecond() . $this->createNoncestr(10);

        switch ($type) {
            case 1:
                $model = new ElectricityBill();
                $body = '缴费通知-电费缴费';
                break;
            case 2:
                $model = new WaterBill();
                $body = '缴费通知-水费缴费';
                break;
            case 3:
                $model = new GasBill();
                $body = '缴费通知-气费缴费';
                break;
            case 4:
                $model = new NetBill();
                $body = '缴费通知-网费缴费';
                break;
            case 5:
                $model = new EstateBill();
                $body = '缴费通知-物业费缴费';
                break;
            default:
                die;
        }

        $detail = $model->detail($bill_id);
        $data['out_trade_no'] = $out_trade_no;
        $model->m_update($bill_id, $data);
        $total_fee = ($detail['cost'] < 0) ? 0.00 : $detail['cost'];

        // 实例微信支付基类
        $weixinPay = new WeixinPay($openid, $body, $total_fee, $out_trade_no);
        // 发起微信支付
        $result = $weixinPay->pay();

        /**
         * @todo 获取下条数据
         */
        $data = [];
        returnJson(200,$result, $data)->send();die;
    }

    /**
     * @param int $length
     * @return string
     */
    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取所有签订的合同的所有房源号
     */
    public function billRoomNumber() {
        $input = input();
        $validate = new Validate([
            ['token', 'require', 'token不能为空'],
            ['id', 'require', '用户id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $this->is_prohibit($id);
        /**
         * 根据小程序中的用户id找到租户id
         */
        $model_t = new TenantManagement();
        $tenant_info = $model_t->detail($id);
        $tenant_id = $tenant_info['tenant_id'];

        /**
         * 根据租客id找到合同id
         */
        $model = new ContracTmanagement();
        $detail = $model->tenantContractId2($tenant_id);
        $data = [];
        foreach ($detail as $k => $contracInfo) {
            /**
             * 根据合同id找到相关信息
             */
            $detail1 = $model->T_One($contracInfo['t_c_mid']);
            // 房号
//            if ($detail1['c_state'] == 6) continue;
            foreach ($detail1['housing'] as $value) {
                array_push($data, $value['c_number']);
            }
        }
//        $data = [
//            "1-1-404"
//        ];

        returnJson(200,"成功", $data)->send();die;
    }

    /**
     * 获取指定时间段的某个房间的所有账单清单
     */
    public function billTimeList() {
        $input = input();
        $validate = new Validate([
            ['token', 'require', 'token不能为空'],
//            ['room_number', 'require', '房间号不能为空'],
            ['time', 'require', '时间不能为空'],
            ['id', 'require', '用户id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }
        if (empty($input['room_number'])) {
            returnJson(200,'操作成功', [])->send();die;
        }

        $room_number = explode('-', $input['room_number']);
        $tung_num = $room_number[0];
        $unit_num = $room_number[1];
        $room_number = $room_number[2];
        $time = $input['time'];
        $id = $input['id'];
        $this->is_prohibit($id);

        $model = new TenantManagement();
        $detail = $model->detailKeeper($id);
        $tenant_id = $detail['tenant_id'];

        $model_e = new ElectricityBill();
        $model_w =  new WaterBill();
        $model_g =  new GasBill();
        $model_n = new NetBill();
        $model_s =  new EstateBill();

        $list_e = $model_e->indexTime($tung_num, $unit_num, $room_number, $time, $tenant_id);
        $list_w = $model_w->indexTime($tung_num, $unit_num, $room_number, $time, $tenant_id);
        $list_g = $model_g->indexTime($tung_num, $unit_num, $room_number, $time, $tenant_id);
        $list_n = $model_n->indexTime($tung_num, $unit_num, $room_number, $time, $tenant_id);
        $list_s = $model_s->indexTime($tung_num, $unit_num, $room_number, $time, $tenant_id);
        $list = array_merge_recursive($list_e, $list_w, $list_g, $list_n, $list_s);

        foreach ($list as &$a) {
            $a['create_time'] = date("Y-m-d H:i", $a['create_time']);
        }

        returnJson(200,'操作成功', $list)->send();die;
    }

    /**
     * 获取某种费用的指定类型的账单清单
     */
    public function billList() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', '用户id不能为空'],
            ['token', 'require', 'token不能为空'],
            ['type', 'require', '缴费类型不能为空'],
            ['status', 'require', '缴费状态不能为空'],
            ['page', 'require', '页码不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];// 用户id
        $type = $input['type'];// 1:电费 2:水费 3:气费 4:网费 5:物业费
        $status = $input['status']; // 1:未缴 2:已缴、补缴
        $page = $input['page'];
        $this->is_prohibit($id);
        $model = $this->getBillModel($type);

        /**
         * 根据小程序中的用户id找到租户id
         */
        $model_t = new TenantManagement();
        $tenant_info = $model_t->detail($id);
        $tenant_id = $tenant_info['tenant_id'];
//        $tenant_id = 26;

        $list = $model->index_tenant_id($tenant_id, $page, $status);
        if ($list['total'] == 0) {
            $list['no_more'] = true;
        } else {
            if ((count($list['data']) + (($page-1) * get_list_rows())) == $list['total']) $list['no_more'] = true;
            else $list['no_more'] = false;
        }

        foreach ($list['data'] as &$a) {
            $a['bill_type'] = $type;
            $a['time'] = date("Y-m-d H:i", $a['time']);
            $a['create_time'] = date("Y-m-d H:i", $a['create_time']);
        }

        returnJson(200,'操作成功', $list)->send();die;
    }

    /**
     * 获取某个账单的详情
     */
    public function billDetail() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['token', 'require', 'token不能为空'],
            ['type', 'require', '账单类型不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];// 账单id
        $type = $input['type'];
        $this->is_prohibit(get_user_id($input['token']));
        $model = $this->getBillModel($type);

        $detail = $model->detail($id);
        $detail['time'] = date("Y-m-d H:i", $detail['time']);
        $detail['create_time'] = date("Y-m-d H:i", $detail['create_time']);
        returnJson(200,'操作成功', $detail)->send();die;
    }

    private function getBillModel($type) {
        switch ($type) {
            case 1:
                return new ElectricityBill();
            case 2:
                return new WaterBill();
            case 3:
                return new GasBill();
            case 4:
                return new NetBill();
            case 5:
                return new EstateBill();
        }
    }

    /**
     * 获得月份
     * @throws \think\Exception
     */
    public function getMonth() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $this->is_prohibit($id);
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        $start_time = $detail['create_time'];
//        $end_time = time();
//        $time = [];
//
//        $start    = new \DateTime(date('Y-m-d', $start_time));
//        $end      = new \DateTime(date('Y-m-d', $end_time));
//        $interval = \DateInterval::createFromDateString('1 month');
//        $period   = new \DatePeriod($start, $interval, $end);
//        foreach ($period as $dt) {
//            array_unshift($time, $dt->format("Y-m"));
//        }
//        if (!in_array(date("Y-m"), $time)) {
//            array_unshift($time, date("Y-m"));
//        }

        returnJson(200,'操作成功', intval($start_time))->send();die;
    }

    /**
     * 一键缴费
     */
    public function onePay() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['bill_ids', 'require', '账单id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $this->is_prohibit($id);
        $bill_ids = $input['bill_ids'];
        $model = new HouseKeeper();
        $detail = $model->detail($id);

        $openid = $detail['open_id'];
        $out_trade_no = getMicrosecond() . $this->createNoncestr(10);
        $total_fee = 0.00;

        foreach ($bill_ids as $k => $bill_id) {
            switch ($k) {
                case 'id_one':
                    $model = new ElectricityBill();
                    break;
                case 'id_two':
                    $model = new WaterBill();
                    break;
                case 'id_three':
                    $model = new GasBill();
                    break;
                case 'id_four':
                    $model = new NetBill();
                    break;
                case 'id_five':
                    $model = new EstateBill();
                    break;
                default:
                    die;
            }

            foreach ($bill_id as $value) {
                $detail = $model->detail($value);
                $data['out_trade_no'] = $out_trade_no;
                $model->m_update($value, $data);
                $total_fee += $detail['cost'];
            }

        }

        // 实例微信支付基类
        $total_fee = $total_fee < 0.00 ? 0.00 : $total_fee;
        $body = '缴费通知-一键缴费';
        $weixinPay = new WeixinPay($openid, $body, $total_fee, $out_trade_no);
        // 发起微信支付
        $result = $weixinPay->pay();

        returnJson(200,$result)->send();die;
    }

    /**
     * 判断是否被禁用
     */
    private function is_prohibit($id) {
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        if ($detail['status'] == 3) {
            returnJson(-3001,"用户不存在")->send();die;
        } elseif ($detail['status'] == 2) {
            returnJson(-3000,"用户被禁用")->send();die;
        } else {

        }
    }
}
